package com.marvels.financial.loan.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import cn.hutool.core.date.DateUtil;
import com.marvels.common.utils.*;
import com.marvels.financial.loan.dto.*;
import com.marvels.financial.pay.bfpay.dto.BankTransactionDto;
import com.marvels.financial.pay.bfpay.dto.BaoFuDirectPaymentDTO;
import com.marvels.financial.pay.bfpay.service.BfPayApi;
import com.marvels.loanapply.dao.AcLoanApplyInfoDao;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.marvels.common.constants.LoanStateConstant;
import com.marvels.common.constants.PageConstant;
import com.marvels.common.constants.PatternType;
import com.marvels.common.constants.SystemParamsConstant;
import com.marvels.common.dto.MarvelsResultDTO;
import com.marvels.common.dto.SynLoanStatus2ApplyDTO;
import com.marvels.common.dto.UserDTO;
import com.marvels.common.dto.pay.McfeRepaymentTradeDetails;
import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.exception.MarvelsErrorCode;
import com.marvels.financial.consum.FinancialConsumerApproveApi;
import com.marvels.financial.consum.FinancialConsumerLoanApplyApi;
import com.marvels.financial.consum.FinancialConsumerProductApi;
import com.marvels.financial.consum.FinancialConsumerSystemApi;
import com.marvels.financial.consum.FinancialConsumerUmApi;
import com.marvels.financial.funds.dao.IFundDao;
import com.marvels.financial.funds.dto.FundDTO;
import com.marvels.financial.loan.api.FinancialILoanAfterInfoApi;
import com.marvels.financial.loan.dao.McfeLendingProcessDao;
import com.marvels.financial.loan.dao.McfeLendingProcessStatusDao;
import com.marvels.financial.loan.service.ILoanApplyMqProduct;
import com.marvels.financial.loan.service.LoanAuditApi;
import com.marvels.financial.loan.service.LoanPaymentApi;
import com.marvels.financial.loan.service.LoanQueryApi;
import com.marvels.financial.pay.dao.McfeRepaymentTradeDetailsMapper;

import net.sf.json.JSONObject;



/**
 * 放款查询
 *
 * @author tangpw
 *
 */
@Service
public class LoanQueryImpl implements LoanQueryApi {

	@Autowired
	private ILoanApplyMqProduct iLoanApplyMqProduct;

	@Autowired
	private IFundDao iFundDao;

	@Autowired
	private LoanAuditApi loanAuditApi;

	@Autowired
	private FinancialConsumerUmApi consumerUmApi;

	@Autowired
	private FinancialConsumerProductApi consumProductApi;

	@Autowired
	private McfeLendingProcessStatusDao mcfeLendingProcessStatusMapper;

	@Autowired
	private McfeLendingProcessDao mcfeLendingProcessMapper;

	@Autowired
	private FinancialConsumerSystemApi consumerSystemApi;

	@Autowired
	private LoanPaymentApi loanPaymentApi;

	@Autowired
	private FinancialConsumerApproveApi financialConsumerApproveApi;

	@Autowired
	private FinancialConsumerApproveApi consumerApproveApi;

	@Autowired
	private FinancialILoanAfterInfoApi loanAfterInfoApi;

	@Autowired
	private FinancialConsumerLoanApplyApi consumerLoanApplyApi;

	@Autowired
	private McfeRepaymentTradeDetailsMapper mcfeRepaymentTradeDetailsMapper;
	@Autowired
	private AcLoanApplyInfoDao acLoanApplyInfoDao;
	@Autowired
	private BfPayApi bfPayApi;

	@Override
	public Map<String, Object> listScreenCondition() throws MarvelsBusinessException{
		Map<String, Object> map = new HashMap<String, Object>();
		List<FundDTO> fundSourceList = iFundDao.select(new FundDTO());// 资金源结果
		List<McptProductType> productList  = consumProductApi.mcptProductTypeInfo(new McptProductType());
		map.put("productList", productList);
		map.put("fundList", fundSourceList);
		map.put("loanQueryPaymentStatus", mcfeLendingProcessStatusMapper.seletAllStatus());
		return map;
	}

	@Override
	public MarvelsResultDTO loanQueryList(LoanAuditConditionDto loanAuditConditionDto) throws MarvelsBusinessException{
		int pageSize = Integer.parseInt(loanAuditConditionDto.getPageSize());
		int pageNum = Integer.parseInt(loanAuditConditionDto.getPageNum());
		if (pageSize < 1) {
			pageSize = PageConstant.PAGESIZE;
		}
		if (pageNum < 1) {
			pageNum = PageConstant.CURRPAGE;
		}
		PageHelper.startPage(pageNum,pageSize);

		//判断该角色是否有权限操出账否决
		Page<McfeLendingProcess> list=mcfeLendingProcessMapper.selectLendProcessList(loanAuditConditionDto);
		if(CollectionUtils.isNotEmpty(list)){
			for(McfeLendingProcess process:list){
				McfeRepaymentTradeDetails details=mcfeRepaymentTradeDetailsMapper.selectByReqNo(process.getReqNo());
				if(details!=null){
					process.setErrorMsg(details.getErrorMsg());
				}
			}
		}
		boolean jurisdiction=false;
		try {
			jurisdiction=jurisdiction(SystemParamsConstant.REJECT_USER_LIST);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>判断当前角色是否有权限操出账否决权限异常:",e);
		}
		String flag ="";
		if(jurisdiction){
			flag="1";
		}
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("data",list);
		map.put("total",list.getTotal());
		McfeLendingProcess dto = mcfeLendingProcessMapper.selectLendProcessAmountStatic(loanAuditConditionDto);
		List<McfeLendingProcess> staticList=new ArrayList<McfeLendingProcess>();
		staticList.add(dto);
		map.put("static",staticList);
		return MarvelsResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(), MarvelsErrorCode.SUCCESS.getDesc(),
				map);
	}

	/**
	 * 判断当前角色是否有权限操作当前对应功能
	 * @param jurisdictionConstant
	 * @return
	 * @throws MarvelsBusinessException
	 */
	private boolean jurisdiction(String jurisdictionConstant) throws MarvelsBusinessException{
		McsmSystemParam mcsmSystemParam = new McsmSystemParam();
		mcsmSystemParam.setParamNames(new String[] { jurisdictionConstant });
		List<McsmSystemParam> paramList = consumerSystemApi.paramList(mcsmSystemParam);
		if (paramList != null && paramList.size() > 0) {
			String[] roleList = paramList.get(0).getParamValue().split(",");
			// 查询当前用户所处角色
			UserDTO userDTO = CacheUtils.getCacheUser();
			SysUserDTO sysUserDTO = consumerSystemApi.querySysUser(userDTO.getUserId());
			List<SysUserRoleDTO> list = sysUserDTO.getRoles();
			for (int i = 0; i < roleList.length; i++) {// 判断该用户是否有权限挂起
				for (SysUserRoleDTO roleDTO : list) {
					if (roleList[i].equals(roleDTO.getRoleCode())) {
						return true;
					}
				}
			}
		}
		return false;
	}


	@Override
	public HSSFWorkbook exportExcel(LoanAuditConditionDto loanAuditConditionDto) throws MarvelsBusinessException{

		List<McfeLendingProcess> list = mcfeLendingProcessMapper.selectLendProcessList(loanAuditConditionDto);

		return getExcel(list);
	}


	public HSSFWorkbook getExcel(List<McfeLendingProcess> list) throws MarvelsBusinessException{
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("放款查询数据一览表");
		HSSFRow row = sheet.createRow((int) 0);
		sheet.setDefaultColumnWidth(10);
		// 创建单元格，并设置值表头 设置表头居中
		HSSFCellStyle style = wb.createCellStyle();
		// 居中格式、加粗
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		org.apache.poi.hssf.usermodel.HSSFFont font = wb.createFont();
		font.setFontHeightInPoints((short) 11);
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		style.setBorderBottom((short) 1);// 下边框
		style.setBorderLeft((short) 1);// 左边框
		style.setBorderRight((short) 1);// 右边框
		style.setBorderTop((short) 1);// 上边框
		style.setLocked(true);
		style.setFont(font);
		// 设置表内容格式
		HSSFCellStyle style2 = wb.createCellStyle();
		style2.setBorderBottom((short) 1);// 下边框
		style2.setBorderLeft((short) 1);// 左边框
		style2.setBorderRight((short) 1);// 右边框
		style2.setBorderTop((short) 1);// 上边框
		style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		HSSFCell cell = row.createCell(0);
		cell.setCellValue("姓名");
		cell.setCellStyle(style);
		cell = row.createCell(1);
		cell.setCellValue("身份证");
		cell.setCellStyle(style);
		cell = row.createCell(2);
		cell.setCellValue("贷款编号");
		cell.setCellStyle(style);
		cell = row.createCell(3);
		cell.setCellValue("银行卡号");
		cell.setCellStyle(style);
		cell = row.createCell(4);
		cell.setCellValue("开户行");
		cell.setCellStyle(style);
		cell = row.createCell(5);
		cell.setCellValue("产品");
		cell.setCellStyle(style);
		cell = row.createCell(6);
		cell.setCellValue("贷款金额");
		cell.setCellStyle(style);
		cell = row.createCell(7);
		cell.setCellValue("到手金额");
		cell.setCellStyle(style);
		cell = row.createCell(8);
		cell.setCellValue("咨询费");
		cell.setCellStyle(style);
		cell = row.createCell(9);
		cell.setCellValue("放款审核通过时间");
		cell.setCellStyle(style);
		cell = row.createCell(10);
		cell.setCellValue("放款申请时间");
		cell.setCellStyle(style);
		cell = row.createCell(11);
		cell.setCellValue("申请人");
		cell.setCellStyle(style);
		cell = row.createCell(12);
		cell.setCellValue("资金方");
		cell.setCellStyle(style);
		cell = row.createCell(13);
		cell.setCellValue("状态");
		cell.setCellStyle(style);
		cell = row.createCell(14);
		cell.setCellValue("渠道");
		cell.setCellStyle(style);
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				McfeLendingProcess process = list.get(i);
				row = sheet.createRow((int) i + 1);
				// 创建单元格，并设置值
				row.createCell(0).setCellValue(process.getCustName());
				row.createCell(1).setCellValue(process.getCustCardNo());
				row.createCell(2).setCellValue(process.getLoanId());
				row.createCell(3).setCellValue(process.getReceiveAcctNo());
				row.createCell(4).setCellValue(process.getReceiveBankName());
				row.createCell(5).setCellValue(process.getProductName());
				row.createCell(6).setCellValue(process.getPrincipalAmtAct() + "");
				row.createCell(7).setCellValue(process.getAviAmount() + "");
				row.createCell(8).setCellValue(process.getConsultingFee() + "");
				row.createCell(9).setCellValue(DateUtils.getDateStr(process.getPassTime(), "yyyy-MM-dd"));
				row.createCell(10).setCellValue(DateUtils.getDateStr(process.getLoanTime(), "yyyy-MM-dd"));
				row.createCell(11).setCellValue(list.get(i).getCreatedBy());
				row.createCell(12).setCellValue(list.get(i).getFundName());
				List<McfeLendingProcessStatus> allStatus=mcfeLendingProcessStatusMapper.seletAllStatus();
				for(McfeLendingProcessStatus mcfeLendingProcessStatus:allStatus){
					if(mcfeLendingProcessStatus.getStatus().equals(process.getStatus())){
						row.createCell(13).setCellValue(mcfeLendingProcessStatus.getStatusName());// 状态
					}
				}
				row.createCell(14).setCellValue(process.getChannelName());
			}
		}
		return wb;

	}
	/**
	 *
	* @Title: loanPayment
	* @Description:线下放款 -- 放款查询列表里面的放款操作
	* @param loanId
	* @return
	* @throws MarvelsBusinessException
	* @author 李瑶
	* @date 2018年10月26日 下午1:50:31
	 */
	@Override
	@Transactional(rollbackFor=Exception.class)
	public  MarvelsResultDTO loanPayment(String loanId) throws MarvelsBusinessException {
		long threadId=Thread.currentThread().getId();
		String batName = Thread.currentThread().getId() + UUID.randomUUID().toString().replace("-", "");
		int count = mcfeLendingProcessMapper.updateBatNameByLoanId(batName, String.valueOf(threadId), "F3", loanId);// 代付失败的
		if (count < 1) {
			throw new MarvelsBusinessException("订单处理中清稍后");
		}
		// 查询进件表信息
		McamLoanApplyInfoDTO applyInfoDTO = new McamLoanApplyInfoDTO();
		applyInfoDTO.setLoanId(loanId);
		McamLoanApplyInfoDTO infoDTO = financialConsumerApproveApi.selectLoanApplyInfo(applyInfoDTO);
		// 不需要修改进件表状态(直接生成还款计划生成还款计划修改) 调用生成还款计划
		try {
			LoanAfterInfoDTO LoanAfterInfoDTO = new LoanAfterInfoDTO();
			LoanAfterInfoDTO.setLoanId(loanId);
			LoanAfterInfoDTO.setProductCode(infoDTO.getProductCode());
			LoanAfterInfoDTO.setFundSource(infoDTO.getFundCode());
			LoanAfterInfoDTO.setTenor(infoDTO.getApplyTerms());
			LoanAfterInfoDTO.setDate(new Date());
			LoanAfterInfoDTO.setAmount(infoDTO.getPrincipalAmtAct());
			LoanAfterInfoDTO.setFundName(infoDTO.getFundName());//资金源名称
			LoanAfterInfoDTO.setProductName(infoDTO.getProductName());//产品小类名称
			LoanAfterInfoDTO.setCustCardNo(infoDTO.getCustCardNo());//客户身份证号
			LoanAfterInfoDTO.setCustName(infoDTO.getCustName());//客户名称
			LoanAfterInfoDTO.setChannelCode(infoDTO.getChannel());//渠道code
			LoanAfterInfoDTO.setChannelName(infoDTO.getChannelName());//渠道名称
			LoanAfterInfoDTO.setProductType(infoDTO.getProductType());//产品大类code
			LoanAfterInfoDTO.setProductTypeName(infoDTO.getProductTypeName());//产品大类名称
			LoanAfterInfoDTO.setMobile(infoDTO.getMobileNo());//客户电话
			LoanAfterInfoDTO.setPaymentBankBranch(infoDTO.getPaymentBankBranch());//还款账户分行联行号
			LoanAfterInfoDTO.setPaymentBankHead(infoDTO.getPaymentBankHead());//还款账户总行联行号
			LoanAfterInfoDTO.setPaymentAcctNo(infoDTO.getPaymentAcctNo());//还款账户卡号
			LoanAfterInfoDTO.setPaymentBankName(infoDTO.getPaymentBankName());//还款账户开户行名称
			LoanAfterInfoDTO.setPaymentAcctName(infoDTO.getPaymentAcctName());//还款账户名称
			LoanAfterInfoDTO.setPatternType(infoDTO.getPatternCode());
			loanAfterInfoApi.loanApplySuccess(LoanAfterInfoDTO);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>>loanId:" + "loanId" + "手动代付处理生成还款计划异常:", e);
			throw new MarvelsBusinessException("生成还款计划异常");
		}
		UserDTO user = CacheUtils.getCacheUser();
		McfeLendingProcess process = new McfeLendingProcess();
		process.setStatus("F4");
		process.setUpdatedBy(user.getUserName());
		process.setOriginalStatus("F3");
		process.setLoanId(loanId);
		process.setPassTime(new Date());
		//新增 ac_loan_apply_info 	money_hand_out_uid
		try {
			String reloanFlag =  consumerLoanApplyApi.synchroMoneyHandOutTime(loanId);
			process.setReloanFlag(reloanFlag);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>>loanId:" + loanId + "同步到进件表的放款时间失败:", e);
		}

		int countInsert = mcfeLendingProcessMapper.updateAuditResult(process);
		if (countInsert < 1) {
			throw new MarvelsBusinessException("更新审核信息失败");
		}
		if (!loanAuditApi.auditCommonDeal(loanId, "F4", "F3", "手动放款", user)) {
			throw new MarvelsBusinessException("手动放款操作异常");
		}
		return MarvelsResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(),"手动放款成功", null);
	}

	@Override
	public  MarvelsResultDTO checkStatus(String loanId) throws MarvelsBusinessException {
		McfeLendingProcess mcfeLendingProcess = mcfeLendingProcessMapper.selectByloanIdAndStatus(loanId, "F10");//
		if (mcfeLendingProcess == null) {
			throw new MarvelsBusinessException("订单无审核记录");
		}
		//将当前查询置为处理中
		long threadId = Thread.currentThread().getId();
		String batName = threadId + "-" + UUID.randomUUID().toString().replace("-", "");
		int count=mcfeLendingProcessMapper.updateBatNameByLoanId(batName,threadId+"", "F10",loanId);
		if(count<1){
			throw new MarvelsBusinessException("处理中请稍候");
		}
		// 调用放款查询服务
		loanPaymentApi.loanPaymentQuery(loanId);

		return MarvelsResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(), "查询成功", null);
	}



	/**
	 * 出账否决
	 * @param dto
	 * @throws MarvelsBusinessException
	 */
	@Override
	@Transactional(rollbackFor=Exception.class)
	public  void accountVeto(LoanAuditConditionDto dto) throws MarvelsBusinessException {
		String loanId=dto.getSingleLoanId();
		String rejectReason=dto.getRejectReason();
		//修改放款审核表状态
		UserDTO user = CacheUtils.getCacheUser();
		McfeLendingProcess process = new McfeLendingProcess();
		process.setUpdatedBy(user.getUserCode());
		process.setOriginalStatus("F3");
		process.setStatus("F15");
		process.setLoanId(loanId);
		process.setMsg(rejectReason);
		int countInsert = mcfeLendingProcessMapper.updateAuditResult(process);
		if (countInsert < 1) {
			throw new MarvelsBusinessException("更新审核信息失败");
		}
		//添加审核记录
		boolean isSuccess=loanAuditApi.auditCommonDeal(loanId, "F15","F3", "出账否决", null);
		if(!isSuccess){
			throw new MarvelsBusinessException("添加审核记录失败");
		}
//		修改进件表状态
//		McamLoanApplyInfoDTO mcamLoanApplyInfoDTO=new McamLoanApplyInfoDTO();
//		mcamLoanApplyInfoDTO.setStatus("F81");
//		mcamLoanApplyInfoDTO.setLoanId(loanId);
//		int count=consumerApproveApi.modifyLoanApplyInfo(mcamLoanApplyInfoDTO);
//		if(count<1){
//			throw new MarvelsBusinessException("更新进件表状态失败");
//		}
		//更新ac_trace状态为取消放款
		SynLoanStatus2ApplyDTO synLoanStatus2ApplyDTO=new SynLoanStatus2ApplyDTO();
		synLoanStatus2ApplyDTO.setLoanId(loanId);
		synLoanStatus2ApplyDTO.setOriginalState(LoanStateConstant.F03);
		synLoanStatus2ApplyDTO.setStatus(LoanStateConstant.F81);
		iLoanApplyMqProduct.synLoanStatus2Apply(synLoanStatus2ApplyDTO);
	}

	@Override
	public List<McptProductMappedDto> changeFundList(LoanAuditConditionDto loanAuditConditionDto) throws MarvelsBusinessException {
		//先判断是否能更换资金源
		String loanId=loanAuditConditionDto.getSingleLoanId();
		McamLoanApplyInfoDTO infoDTO=new McamLoanApplyInfoDTO();
		infoDTO.setLoanId(loanId);
		infoDTO=consumerApproveApi.selectLoanApplyInfo(infoDTO);
		if(infoDTO==null){
			throw new MarvelsBusinessException("进件信息不存在");
		}
		McfeLendingProcess mcfeLendingProcess=mcfeLendingProcessMapper.selectByloanIdAndStatus(loanId, "");//
		if(mcfeLendingProcess==null){
			throw new MarvelsBusinessException("审核信息不存在");
		}
		if(!mcfeLendingProcess.getStatus().equals("F3") && !mcfeLendingProcess.getStatus().equals("F0")){
			throw new MarvelsBusinessException("状态不符合更换资金源条件");
		}
		if(StringUtils.isNotEmpty(infoDTO.getPatternCode()) && infoDTO.getPatternCode().equals(PatternType.XIANSHANGPRODUCT.getPatternTypeCode())){
			throw new MarvelsBusinessException("此件是线上产品,不能做资金源更换");
		}
		//查询出可以更换的资金源列表
		McptProductMappedDto mappedDto=new McptProductMappedDto();
		mappedDto.setChannel(infoDTO.getChannel());
		mappedDto.setProductType(infoDTO.getProductType());
		mappedDto.setProductCode(infoDTO.getProductCode());
		mappedDto.setGrate(infoDTO.getRiskCustomerType());
		mappedDto.setTenor(infoDTO.getApplyTerms()+"");
		List<String> limitFundList=Arrays.asList(CommonProperties.getLimitFundList().split(","));
		mappedDto.setLimitFundList(limitFundList);
		List<McptProductMappedDto> list=consumProductApi.selectProductMappedInfo(mappedDto);
		return list;
	}

	@Override
	public Page<BankTransactionDto> mcamLoanBankFlowQuery(LoanBankTransactionDto loanBankTransactionDto) throws MarvelsBusinessException {
		int pageSize=loanBankTransactionDto.getPageSize();
		int pageNum=loanBankTransactionDto.getPageNum();
		if ( pageSize< 1) {
			pageSize=PageConstant.PAGESIZE;
		}
		if (pageNum< 1) {
			pageNum=PageConstant.CURRPAGE;
		}
		PageHelper.startPage(pageNum, pageSize);

		return acLoanApplyInfoDao.mcamLoanBankFlowQuery(loanBankTransactionDto);
	}

	@Override
	public void replaceFundResource(LoanAuditConditionDto loanAuditConditionDto) throws MarvelsBusinessException {
		String fundCode = loanAuditConditionDto.getFundSourceCode();
		String loanId = loanAuditConditionDto.getSingleLoanId();
		if(StringUtils.isEmpty(fundCode)){
			throw new MarvelsBusinessException("更换资金源不能为空");
		}
		//将审核状态更新未更换资金源
		McfeLendingProcess process = new McfeLendingProcess();
		process.setLoanId(loanId);
		process.setStatus("F11");
		int countInsert = mcfeLendingProcessMapper.updateAuditResult(process);
		if(countInsert<1){
			throw new MarvelsBusinessException("更新审核状态为更换资金源失败");
		}
		//更新进件表状态为P06
		McamLoanApplyInfoDTO infoDTO=new McamLoanApplyInfoDTO();
		infoDTO.setLoanId(loanId);
		infoDTO.setStatus("P06");
		infoDTO.setOriginalState("F03");
		infoDTO.setFundCode(fundCode);
		UserDTO userDTO=CacheUtils.getCacheUser();
		infoDTO.setUpdatedBy(userDTO.getUserCode());
		infoDTO.setUpdatedDate(new Date());
//		int count=consumerApproveApi.modifyLoanApplyInfo(infoDTO);
//		if(count<1){
//			throw new MarvelsBusinessException("更新进件信息状态失败");
//		}

		//设置合同协议标题、内容、url等信息
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("titleDesc", CommonProperties.getLoanContractTitle());
		String protocolUrl = CommonProperties.getLoanContractReqUrl();
		//获取此进件单所有需要签署协议列表
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		Map<String,String> compactMap;
		List<ProtocolTemplateInfoDTO> templateList=consumerApproveApi.findProtocalTemplateList(infoDTO);
		if(templateList!=null && templateList.size()>0){
			for(ProtocolTemplateInfoDTO templateInfoDTO:templateList){
				compactMap = new HashMap<String,String>();
				compactMap.put("titleDesc", templateInfoDTO.getTemplateAbbr());
				compactMap.put("protocolDesc", templateInfoDTO.getTemplateAbbr());
				StringBuilder sbUrl = new StringBuilder(protocolUrl);
				sbUrl.append(loanId).append("/").append(templateInfoDTO.getTemplateNo());
				compactMap.put("protocolUrl", sbUrl.toString());
				list.add(compactMap);
			}
		}
		param.put("loanId", loanId);
		param.put("compactList", list);
		//获取短链接
		String shortUrl = consumerUmApi.insertShortUrl(JSONObject.fromObject(param).toString() , loanId);
		McamLoanApplyInfoDTO applyInfoDTO=new McamLoanApplyInfoDTO();
		applyInfoDTO.setLoanId(loanId);
		applyInfoDTO=consumerApproveApi.selectLoanApplyInfo(infoDTO);
		//发送短链接信息
	    shortUrl = CommonProperties.getShortReqUrl()  + shortUrl;
	    User custUser = consumerUmApi.queryUserByMobileNo(applyInfoDTO.getMobileNo(), "2");//得到客户消息
	    if(custUser == null){
	    	RealNameAuthentication  rauth = consumerUmApi.querByIdentiyCardNo(applyInfoDTO.getCustCardNo());
		    custUser=consumerUmApi.queryUserById(rauth.getUserId());
	    }
	    //给客户推一条信息
	    Map<String,String> p1 =new HashMap<String,String>();
	    p1.put("title", "云科贷提醒"); // 标题
	    p1.put("userId", custUser.getId()+""); // 客户id
	    p1.put("type", "2"); // 推送消息类型
	    p1.put("targetAlias", custUser.getCid()+""); // 推送人id, 推送目标
	    p1.put("pushCategory", "1");
	    p1.put("permeate", "尊敬的 "+applyInfoDTO.getCustName()+" 先生/女士，您好！为提升放款速度，已为您更换放款通道，现需重新签署相关协议及合同，请进入“首页->申请进度->修改资金源->去签合同”，进行签署确认。一经签署确认，原协议及合同终止。"); // 推送内容请点击 "+shortUrl+"
	    p1.put("targetUrl", "sms");
	    p1.put("messageCategory", "00005");
	    //给客户经理推一条
		Map<String,String> paramUser = new HashMap<String,String>();
		User user1 = consumerUmApi.queryUserById(Integer.parseInt(applyInfoDTO.getEmployeeId()));
		paramUser.put("title", "云科贷提醒"); // 标题
		paramUser.put("userId", user1==null?"-1":user1.getId()+""); // 客户id
		paramUser.put("type", "2"); // 推送消息类型
		paramUser.put("targetAlias", user1==null?"-1":user1.getCid());  // 推送人id, 推送目标
		paramUser.put("pushCategory", "1");
		paramUser.put("permeate", "您的客户"+applyInfoDTO.getCustName()+" 已更换放款通道，现需重新签署相关协议及合同，请尽快联系客户重新签署合同，谢谢！"); // 推送内容
		paramUser.put("targetUrl", "sms");
		paramUser.put("messageCategory", "00005");
//		consumerExternalApi.pushFacePush(p1);
//		consumerExternalApi.pushFacePush(paramUser);

		//更新ac_trace状态为正常结清
		SynLoanStatus2ApplyDTO synLoanStatus2ApplyDTO=new SynLoanStatus2ApplyDTO();
		synLoanStatus2ApplyDTO.setLoanId(loanId);
		synLoanStatus2ApplyDTO.setOriginalState(LoanStateConstant.F3);
		synLoanStatus2ApplyDTO.setStatus(LoanStateConstant.F11);
		iLoanApplyMqProduct.synLoanStatus2Apply(synLoanStatus2ApplyDTO);
	}

	@Override
	public void applyBankFlow(LoanBankTransactionDto loanBankTransactionDto) {
		BaoFuDirectPaymentDTO paymentDTO = new BaoFuDirectPaymentDTO();
		paymentDTO.setAmount(loanBankTransactionDto.getOrderMoney());
		paymentDTO.setBankNumber(loanBankTransactionDto.getPayerUnAcctCode());
		paymentDTO.setRealName(loanBankTransactionDto.getPayerUnUserName());
		paymentDTO.setIdNumber(null);
		paymentDTO.setMobile(null);
		paymentDTO.setLoanId(null);
		String orderNo = GenerateReqNoUtils.transctionReq2("BFZZ", 24);
		paymentDTO.setOrderNumber(orderNo);
		paymentDTO.setProtocolNo(null);
		Map<String, Object> map = null;// 走协议代扣
        try {
            map = bfPayApi.baoFuTransPayment(paymentDTO);
			// 更新状态
			if("0000".equals(map.get("errorcode"))){
				BankTransactionDto bankTransactionDto = new BankTransactionDto();
				bankTransactionDto.setApplyTime(DateUtil.now());
				bankTransactionDto.setId(loanBankTransactionDto.getId());
				bankTransactionDto.setLoanBankSerialNo(orderNo);
				bankTransactionDto.setPayerUnAcctCode(loanBankTransactionDto.getPayerUnAcctCode());
				bankTransactionDto.setPayerUnUserName(loanBankTransactionDto.getPayerUnUserName());
				bankTransactionDto.setStatus("2");
				acLoanApplyInfoDao.updateMcamLoanBankFlow(bankTransactionDto);
			}else{
				MarvelsLogUtil.getInstance().info("更新失败");
			}
        } catch (MarvelsBusinessException e) {
            throw new RuntimeException(e);
        }
        MarvelsLogUtil.getInstance().info("转账支付发起结果"+map.toString());
	}

	@Override
	public MarvelsResultDTO onlineLendPayment(String loanId) throws MarvelsBusinessException {
		McfeLendingProcess mcfeLendingProcess=mcfeLendingProcessMapper.selectByloanIdAndStatus(loanId, "F3");//
		if(mcfeLendingProcess==null){
			throw new MarvelsBusinessException("不处于重新放款状态");
		}
		long threadId=Thread.currentThread().getId();
		String batName = Thread.currentThread().getId() + UUID.randomUUID().toString().replace("-", "");
		int count = mcfeLendingProcessMapper.updateBatNameByLoanId(batName, String.valueOf(threadId), "F3", loanId);// 代付失败的
		if (count < 1) {
			throw new MarvelsBusinessException("订单处理中清稍后");
		}
		String auditStatus = "";
		String auditMsg = "";
		//重新放款发起
		PaymentResponse response = new PaymentResponse();
		try {
			response = loanPaymentApi.excuteLoanPayment(loanId,"F3");
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>loanId" + loanId + "线上放款的放款异常:", e);
		}
		if ("1".equals(response.getCode())) {
			auditStatus = "F10";
			auditMsg = "处理中";
		}  else {
			auditStatus = "F3";
			auditMsg = response.getMsg();

		}
		// 持久化审核信息
		McfeLendingProcess process = new McfeLendingProcess();
		process.setOrderNumber(response.getOrderNumber());
		process.setMsg(auditMsg);
		process.setStatus(auditStatus);
		process.setIsBusy("0");// 将审核表状态改为空闲
		process.setFundReturnTime(new Date());
		process.setUpdatedBy("system");
		process.setUpdatedDate(new Date());
		process.setOriginalStatus("F3");
		process.setLoanId(loanId);
		//自动放款
		process.setLendType("1");
		int countInsert = mcfeLendingProcessMapper.updateAuditResult(process);
		if (countInsert < 1) {
			MarvelsLogUtil.getInstance().info(">>>>>>>>>>>>>>loanId" + loanId + ",更新审核信息失败");
			throw new MarvelsBusinessException("更新审核信息失败");
		}
		UserDTO user = CacheUtils.getCacheUser();
		if (!loanAuditApi.auditCommonDeal(loanId,auditStatus, "F3", "线上放款", user)) {
			throw new MarvelsBusinessException("线上放款操作异常");
		}
		return MarvelsResultDTO.getResult(MarvelsErrorCode.SUCCESS.getValue(),auditMsg, null);
	}
}
